#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "err_handle.h"
#include "cln_thread.h"
#define BUF_SIZE 1024
#define NAME_SIZE 128
char g_cln_name[NAME_SIZE];

int main(int argc, char *argv[])
{
    int sock_cln = 0;
    int rv = 0;
    struct sockaddr_in serv_addr = {0};
    pthread_t send_tid;
    pthread_t recv_tid;
    void *thread_return;

    if (argc != 4)
    {
        printf("usage :%s <ip><port><name>. \n", argv[0]);
        return -1;
    }

    strcpy(g_cln_name, argv[3]);

    sock_cln = socket(PF_INET, SOCK_STREAM, 0);
    if (sock_cln == -1)
    {
        error_handling("socket() error. \n");
    }

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(atoi(argv[2]));
    // inet_pton(AF_INET,"127.0.0.1", &serv_addr.sin_addr.s_addr);
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]); //htonl(INADDR_ANY)
    rv = connect(sock_cln, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if (rv == -1)
    {
        error_handling("connect() error .\n");
    }

    pthread_create(&send_tid, NULL, send_thread, (void *)&sock_cln);
    pthread_create(&recv_tid, NULL, recv_thread, (void *)&sock_cln);
    pthread_join(send_tid, &thread_return);
    pthread_join(recv_tid, &thread_return);

    close(sock_cln);
    return 0;
}

//打印客户端ip端口信息
/*char ip[32];
    printf("客户端的IP:%s, 端口:%d\n",
            inet_ntop(AF_INET, &caddr.sin_addr.s_addr,ip,sizeof(ip)),
                ntohs(caddr.sin_port));*/
